package com.three.service;

import com.three.message.item.GetPackItemsReqMessage;
import com.three.domain.item.ItemPo;
import com.three.message.item.GetPackItemsRespMessage;
import com.three.repository.ItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Mathua on 2017/7/17.
 */
@Service
public class ItemService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ItemService.class);

    @Autowired
    private ItemRepository itemRepository;

    public void saveItems(long ownerId, int itemId, Integer count) {
        List<ItemPo> items = itemRepository.findByOwnerId(ownerId);
        items = items.stream().filter(item -> {
            return item.getCfg().getId() == itemId;
        }).collect(Collectors.toList());

        // 加到已有的物品，整合到一起
        Iterator<ItemPo> iter = items.iterator();
        ItemPo itemPo;
        while(iter.hasNext() && count > 0) {
            itemPo = iter.next();
            itemPo.add(count);
        }
        // 创建新的物品
        while(count > 0) {
            itemPo = ItemPo.build(ownerId, itemId, count);
            if(itemPo == null)
                break;
            itemRepository.save(itemPo);
        }
    }

    public void getPackItems(GetPackItemsReqMessage message) {
        List<ItemPo> items = itemRepository.findByOwnerId(message.getConnection().getSessionContext().getPlayerId());
        GetPackItemsRespMessage.from(message).setItems(items).send();
    }
}
